package com.tanhua.server.interceptor;

import cn.hutool.core.codec.Base64Decoder;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.apache.catalina.connector.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

/**
 * 判断token是否有效
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("url = " +  request.getMethod() + request.getRequestURI());
        //获取token
        String token = request.getHeader("Authorization");
        //token校验
        boolean b = JwtUtils.verifyToken(token);
        if (b){
            Claims claims = JwtUtils.getClaims(token);
            long id = ((Integer) claims.get("id")).longValue();
            String mobile = claims.get("mobile").toString();
            User user = new User();
            user.setId(id);
            user.setMobile(mobile);
            UserHolder.set(user);
            //redisTemplate.opsForValue().set(id, System.currentTimeMillis());
            return true;
        }
        response.setStatus(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
